package com.algernoon.nettydemo.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class TimeClient {

	private void connect(String host, int port) throws Exception {
		// 配置客户端NIO线程组
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			// 客户端启动辅助类
			Bootstrap b = new Bootstrap();
			b.group(group).channel(NioSocketChannel.class)
				.option(ChannelOption.TCP_NODELAY, Boolean.TRUE)
				.handler(new ChannelInitializer<SocketChannel>() {
					
					// 直接使用匿名内部类，实现initChannel方法，其作用是当创建NioSocketChannel成功之后，在初始化他的时候
					// 将他的Channelhandler设置到ChannelPipeline中，用于处理网络I/O事件
					@Override
					protected void initChannel(SocketChannel ch) throws Exception {
						ch.pipeline().addLast(new TimeClientHandler());
					}
				});
			
			// 发起异步连接操作（connect发起异步连接，然后调用sync同步方法等待连接成功）
			ChannelFuture f = b.connect(host, port).sync();
			// 关闭客户端链路
			f.channel().closeFuture().sync();
		} catch (Exception e) {
		} finally {
			// 优雅退出，释放NIO线程组
			group.shutdownGracefully();
		}
	}
	
	public static void main(String[] args) throws Exception {
		new TimeClient().connect("127.0.0.1", 8080);
	}
	
}
